# -*- coding: utf8 -*-
__author__ = 'Luoge'

import os,sys
import numpy

# sys.path.append('c:\Program Files (x86)\JetBrains\PyCharm 3.4.1\pycharm-debug.egg')
# import pydevd
# pydevd.settrace('localhost',  port=53100,  stdoutToServer=True,  stderrToServer=True)

scriptPath = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(scriptPath+"/libsvm320/python")
from svmutil import *

# normalize ndarray
def normalizeByArray(featureNum, minmaxArray, newMinValue=0, newMaxValue=1 ):
    def normalizeFunc(x):
        r = {}
        for i in range(featureNum):
            val = ( x[i+1] - minmaxArray[i,0] ) * newMaxValue / (minmaxArray[i,1] - minmaxArray[i,0] ) + newMinValue
            # r=(x-minVal)*newMaxValue/(maxVal-minVal) + newMinValue
            r[i+1] = val
        return r
    return numpy.frompyfunc(normalizeFunc,1,1)

def svmDataScale(inFileName, outFileName, ignoreValue=-99999.0, ignoreValue2=None):
    # pydevd.settrace('localhost',  port=53100,  stdoutToServer=True,  stderrToServer=True)
    yLabel, xdictList = svm_read_problem(inFileName)
    yArray = numpy.array(yLabel)
    xArray = numpy.array(xdictList)
    dataIndexBoolArray = (yArray != ignoreValue)
    if ignoreValue2 is not None:
        dataIndexBoolArray2 = (yArray != ignoreValue2)
        tBoolArray = dataIndexBoolArray & dataIndexBoolArray2
        dataIndexBoolArray = tBoolArray
    tempDataXArray = xArray[dataIndexBoolArray]

    firstEle = xdictList[0]
    featureNum = len(firstEle)
    minmaxValues = numpy.zeros((featureNum,2))

    for xDict in tempDataXArray:
        for i in range(featureNum):
            if xDict[i+1]<minmaxValues[i,0]:
                minmaxValues[i,0] = xDict[i+1]
            elif xDict[i+1] > minmaxValues[i,1]:
                minmaxValues[i,1] = xDict[i+1]
    # print(minmaxValues)
    outufuncXArray = normalizeByArray(featureNum,minmaxValues,0,1)(tempDataXArray) #the result is a ufunc object
    dataXArray = outufuncXArray.astype(dict) # cast ufunc object ndarray to float ndarray

    return dataXArray,dataIndexBoolArray
